package org.bozo.im.service.protocols.xmpp.stanza.task.starttls;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.bozo.im.service.Constants;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.XMPPSessionConfiguration;
import org.bozo.im.service.protocols.xmpp.stanza.task.Task;
import org.bozo.im.service.protocols.xmpp.stanza.util.starttls.SimpleTrustManager;

import android.util.Log;

public class ProceedTask extends Task implements HandshakeCompletedListener {


	private XMPPSession mSession;
	private SSLSocket mSocket;

	public ProceedTask(String pId) {
		super(pId);
	}
	
	@Override
	public void doTask(XMPPSession pSession, StringBuilder pBuilder) throws Exception {

		mSession = pSession;

		SSLContext lContext = SSLContext.getInstance("TLS");

		lContext.init(null, new TrustManager[] {new SimpleTrustManager(null)}, null);

		SSLSocketFactory lFactory = lContext.getSocketFactory();
		XMPPSessionConfiguration lConfiguration = mSession.getConfiguration();

		mSocket = (SSLSocket)lFactory.createSocket(mSession.getSocket(), lConfiguration.getServer(), lConfiguration.getPort(), false);
		mSocket.setSoTimeout(0);
		mSocket.setKeepAlive(true);
		mSocket.addHandshakeCompletedListener(this);
		mSocket.startHandshake();
	}

	public void handshakeCompleted(HandshakeCompletedEvent event) {
		try {
			
			// ---------------------------------------------------------------------------------------
			Log.d(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.task.starttls.ProceedTask.handshakeCompleted ---------- TLS handshake successfull");
			// ---------------------------------------------------------------------------------------
			
			mSession.setSocket(mSocket);
			mSession.startSession();
			
		} catch (Exception e) {
			// ---------------------------------------------------------------------------------------
			Log.e(Constants.ACTIVITY_TAG, "org.bozo.im.xmpp.stanza.task.starttls.ProceedTask.handshakeCompleted ---------- An Exception has been caught: ", e);
			// ---------------------------------------------------------------------------------------
		}
	}
}
